package hong.helloWorld.typeHandlers;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MyDateToStringTypeHandler extends BaseTypeHandler<Date> {

    String format = "yyyy-MM-dd";


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String dateStr = dateFormat.format(parameter);
        ps.setString(i, dateStr);
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {

        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(rs.getString(columnName));
        } catch (Exception e) {
            return null;
        }

    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(rs.getString(columnIndex));
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        try {
            return dateFormat.parse(cs.getString(columnIndex));
        } catch (Exception e) {
            return null;
        }
    }
}
